//
//  UIViewController+AG.swift
//  ASW
//
//  Created by zhuxuhong on 2020/11/22.
//

import UIKit
import BWToolKit

extension UIViewController {
    public var layoutSafeArea: CGRect {
        let insets = Lets.safeAreaInsets
        let size = Lets.screenBounds
        let x = insets.left
        var y = insets.top
        var h = size.height - insets.top - insets.bottom
        let w = size.width - insets.left - insets.right
        if let bar = navigationController?.navigationBar {
            h -= bar.bounds.height
            y += bar.bounds.height
        }
        if let bar = tabBarController?.tabBar {
            h -= bar.bounds.height
        }
        return .init(origin: .init(x: x, y: y), size: .init(width: w, height: h))
    }
}

extension UIViewController {
    public enum CloseType {
        case pop
        case dismiss
        case popAnimated(_ animated: Bool = true, completion: (()->Void)? = nil)
        case dismissAnimated(_ animated: Bool = true, completion: (()->Void)? = nil)
    }
    
    public func closePage(_ type: CloseType = .pop) {
        switch type {
        case .dismiss:
            closePage(.dismissAnimated())
        case .dismissAnimated(let animated, let completion):
            dismiss(animated: animated, completion: completion)
        case .pop:
            closePage(.popAnimated())
        case .popAnimated(let animated, let completion):
            navigationController?.popVC(animated: animated, completion: completion)
        }
    }
}

extension UIViewController {
    public func updateNavBar(
        tintColor: UIColor?,
        barColor: UIColor?,
        isTranslucent: Bool
    ) {
        let bar = navigationController?.navigationBar
        bar?.tintColor = tintColor
        bar?.setBackgroundImage(barColor?.bw_toImage(), for: .default)
        var attrs = bar?.titleTextAttributes
        attrs?[NSAttributedString.Key.foregroundColor] = tintColor
        bar?.titleTextAttributes = attrs
        bar?.isTranslucent = isTranslucent
        bar?.barTintColor = barColor
    }
    
    public func withNavController() -> UINavigationController {
        return .init(rootViewController: self)
    }
    
    public var isNavRootVC: Bool {
        return self == navigationController?.rootViewController
    }
}
